﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kaspersky.Test.RecursiveLinkLogger
{
    /// <summary>
    /// Searches for HTML links in a string using a custom state machine.
    /// Wants 'http://' prefix.
    /// </summary>
    public class StateMachineLinkExtractorWithHttpPrefix : ILinkExtractor
    {
        private const string HttpPrefix = "http://";

        public IEnumerable<string> ExtractLinksFromString(string s)
        {
            var result = new List<string>();

            var stateMachine = new LinkParsingStateMachine();
            stateMachine.LinkFoundEvent += (url) =>
            {
                // The state machine doesn't check the URLs for 'http://' prefix
                // (that would make the machine even more complex).
                // So, here is the right place to filter out links without prefix.
                if 
                (
                    (url.Length > HttpPrefix.Length)
                    &&
                    (url.Substring(0, HttpPrefix.Length).Equals(HttpPrefix, StringComparison.InvariantCultureIgnoreCase))
                )
                {
                    result.Add(url);
                }
            };
            stateMachine.Parse(s);

            return result;
        }
    }
}
